<template>
  <el-dialog
    class="public-dialog"
    title="退款原因管理"
    width="934"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
    style="height: 90vh"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="box">
      <div>
        <XForm ref="form" :formData="model" :fieldList="fieldList" :options="formOptions" :originOption="originOption" />
        <div class="mb-[10px]">
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="primary" @click="handleSwitchStatus(true)"> 启用 </el-button>
          <el-button type="danger" @click="handleSwitchStatus(false)"> 禁用 </el-button>
        </div>
      </div>
      <div class="tabble-box">
        <vxe-table
          class="dialog-table"
          ref="tableRef"
          :data="tableData"
          border="full"
          :round="true"
          :loading="loading"
          :row-config="{ keyField: 'id' }"
          :tree-config="{
            transform: true,
            rowField: 'id',
            parentField: 'parent_id',
          }"
          height="auto"
          :checkbox-config="{ labelField: 'reason' }"
        >
          <vxe-column type="checkbox" title="退款原因" tree-node></vxe-column>
          <vxe-column field="is_enable_desc" title="状态" width="60"> </vxe-column>
          <vxe-column field="create_time" title="添加时间" width="170"></vxe-column>
          <vxe-column field="create_user" title="添加人" width="180"></vxe-column>
          <vxe-column field="operate" title="操作" width="130">
            <template #default="{ row, rowIndex }">
              <el-link type="primary" :underline="false" class="mr-3" @click="handleEdit(row)"> 编辑 </el-link>
              <el-link type="primary" :underline="false" class="mr-3" @click="handleLog(row)"> 日志 </el-link>
              <el-link type="danger" :underline="false" @click="handleDelete(row.id)"> 删除 </el-link>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
    <template #footer>
      <el-button :disabled="loading" @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
  <AddReason v-model="visible" :rows="rows" :edit="!!rows.id" @refresh="refreshList" :option="originOption" />

  <Log dialog v-model="logVisible" :autoLoad="false" tag="refund-reason" :business_id="logId" />
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import AddReason from "./AddReason/index.vue"

import { apiGetPlatform } from "@/api/public"
import { getReasonList, destroyRefund, reasonSwitchStatus } from "../../api/index"
import { nextTick } from "vue"

const props = defineProps({
  modelValue: { type: Boolean, default: false },
})

const emit = defineEmits(["update:modelValue", "refresh", "refreshList"])

const { proxy } = getCurrentInstance()

const tableRef = ref()
const form = ref()
const loading = ref(false)
const tableData = ref([])
const visible = ref(false)
const rows = ref({})
const model = ref({})

// 列表数据
const getTreeList = async () => {
  try {
    loading.value = true
    const res = await getReasonList({
      platform_id: model.value.platform,
    })
    tableData.value = res.data
  } catch (e) {
  } finally {
    loading.value = false
  }
}

const refreshList = () => {
  getTreeList()
  emit("refreshList")
}

// 日志
import Log from "@/components/Log/index.vue"
const logVisible = ref(false)
const logId = ref("")
const handleLog = (item) => {
  logId.value = item.id
  logVisible.value = true
}

const fieldList = ref([
  {
    field: "platform",
    type: "select",
    style: { width: "286px" },
    originField: "platform",
    options: { placeholder: "请选择平台" },
    clearable: false,
    itemProps: {
      onChange: getTreeList,
    },
  },
])
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      getGetPlatform()
    }
  }
)
const originOption = ref({})

onMounted(() => {})

const getGetPlatform = async () => {
  try {
    const { data } = await apiGetPlatform()
    originOption.value.platform = data.map((n) => ({ ...n, label: n.platform_name, value: n.platform_id }))
    model.value.platform = originOption.value.platform?.[0].value
    nextTick(() => {
      getTreeList()
    })
    // }
  } catch (e) {
    console.error(e)
  } finally {
  }
}
// 新增
const handleAdd = () => {
  rows.value = JSON.parse(JSON.stringify({ platform_id: model.value.platform }))
  visible.value = true
}

const handleSave = async () => {
  try {
    loading.value = true
    const formValues = await form.value.submit()
    const orderIds = props.rows?.map((n) => n.id)
    handleClose(true)
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleEdit = (items) => {
  rows.value = JSON.parse(JSON.stringify(items))
  visible.value = true
}

const handleDelete = async (id) => {
  proxy.confirm({
    title: "提示",
    content: "确认删除该条数据吗",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = "处理中.."
          await destroyRefund({ id })
          getTreeList()
        } catch (e) {
          console.error(e)
        } finally {
          instance.confirmButtonLoading = false
          done()
        }
      } else {
        done()
      }
    },
  })
}

const handleSwitchStatus = async (flag) => {
  const getCheckboxRecords = tableRef?.value.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({
      showClose: true,
      message: "请至少选择一条数据！",
      type: "warning",
    })
    return false
  }

  try {
    await reasonSwitchStatus({
      ids: getCheckboxRecords.map((n) => n.id),
      status: flag ? 1 : 0,
    })
    getTreeList()
    tableRef.value?.clearCheckboxRow()
  } catch (e) {
  } finally {
  }
}

const handleClose = (refresh) => {
  emit("update:modelValue", false)
  form.value.resetForm()
  if (refresh) emit("refresh")
}

const formOptions = {
  inline: true,
}
</script>
<style lang="scss" scoped>
.box {
  display: flex;
  flex-direction: column;
  height: 100%;
  height: calc(90vh - 140px);
  .tabble-box {
    height: 100%;
    flex: 1;
  }
}

:deep(.dialog-table) {
  .vxe-tree-cell {
    height: 26px;
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
}
</style>
